package com.wswy.wzcx.module.core;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.che.libcommon.utils.RxBus;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.UserMode;
import com.wswy.wzcx.module.InternalMsgCode;
import com.wswy.wzcx.ui.user.LoginHolderActivity;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.ResourceObserver;

import org.greenrobot.eventbus.EventBus;

public class BasePresenter {

    protected CompositeDisposable disposables = new CompositeDisposable();

    private Bundle bundle;

    public void onCreate(@Nullable Bundle bundle) {
        this.bundle = bundle;
        registerObservers();
        if (autoRegisterEvent()) {
            registerEvent();
        }
    }

    protected Bundle getBundle() {
        return bundle;
    }

    protected void registerObservers() {

        ResourceObserver<UserMode> userLoginObserver = new ResourceObserver<UserMode>() {
            @Override
            public void onNext(UserMode userMode) {
                onUserLoginSuccess(userMode);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };

        ResourceObserver<UserMode> userLogoutObserver = new ResourceObserver<UserMode>() {
            @Override
            public void onNext(UserMode userMode) {
                onLogout();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };


        RxBus.getDefault().toObservableWithCode(InternalMsgCode.CODE_LOGIN_SUCCESS, UserMode.class)
                .subscribe(userLoginObserver);

        RxBus.getDefault().toObservableWithCode(InternalMsgCode.CODE_LOGOUT, UserMode.class)
                .subscribe(userLogoutObserver);

        disposables.add(userLoginObserver);
        disposables.add(userLogoutObserver);
    }


    protected void onUserLoginSuccess(UserMode userMode) {

    }

    protected void onLogout() {

    }

    public boolean hasLogin() {
        return DataCenter.get().hasLogin();
    }

    public void gotoLogin(Context context) {

        context.startActivity(new Intent(context, LoginHolderActivity.class));

    }

    public void onDestroy() {
        disposables.dispose();
        if (autoRegisterEvent()) {
            unregisterEvent();
        }
    }


    public void registerEvent() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    public void unregisterEvent() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    protected boolean autoRegisterEvent() {
        return false;
    }

}
